package com.imist.nettybasic4.server.handler;

import com.imist.nettybasic4.protocol.request.JoinGroupRequestPacket;
import com.imist.nettybasic4.protocol.response.JoinGroupResponsePacket;
import com.imist.nettybasic4.utils.SessionUtils;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
@ChannelHandler.Sharable
public class JoinGroupRequestHandler extends SimpleChannelInboundHandler<JoinGroupRequestPacket> {

    public static final JoinGroupRequestHandler INSTANCE = new JoinGroupRequestHandler();

    protected JoinGroupRequestHandler() {
    }
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, JoinGroupRequestPacket joinGroupRequestPacket) throws Exception {
        //1. 获取群对应的channelGroup,然后将用户的channel添加进去
        String groupId =joinGroupRequestPacket.getGroupId();
        ChannelGroup channels = SessionUtils.getChannelGroup(groupId);
        channels.add(channelHandlerContext.channel());
        // 2. 构造加群响应发送给客户端
        JoinGroupResponsePacket responsePacket =new JoinGroupResponsePacket();
        responsePacket.setSuccess(true);
        responsePacket.setGroupId(groupId);
        channelHandlerContext.writeAndFlush(responsePacket);
    }

}
